'use strict';

    angular.module('app')
        .controller('userUpdateController', ['$scope', '$rootScope', '$state', '$timeout',
                                             function($scope, $rootScope, $state, $timeout) {
        var title = "";
        var defaultAva = $rootScope.defaultAvatar;
        $scope.myImage='';
        // $scope.myCroppedImage=$scope.myCroppedImage ;
        $scope.myCroppedImage = '';
        $rootScope.myUser = null;
        $scope.userData = null;
        if($state.includes('**.user.baseInfoUpdate')){
            title="个人信息编辑";
            //var id = $state.params.id;
            activate();
        }
        $scope.title = $rootScope.title = title;
        $scope.loading = true;
        $scope.save= function(){
            $scope.loading = true;
            validate();
        };
        function saveData(){
             $scope.record.sex=$("input[name='sex']:checked").val();
            var m = $scope.record;
            var bd=document.getElementById("birthDay").value;
            if(bd== null || bd== undefined || bd== ""){
                $scope.birthDay="0000-00-00";
            }
            if(m){
                $scope.isDisabled = true;//提交disabled
                $.ajax({
                	type: 'POST',
    				url : '/user/update/person',
    	            dataType: 'json',
    				contentType:'application/json;charset=UTF-8',
    				data: angular.toJson(m)
    			}).then(callback);
            }
            function callback(result){
                if(result.httpCode ==200){//成功
                	alert("用户信息编辑成功！");
                    toaster.clear('*');
                    toaster.pop('success', '', "保存成功");
                    $timeout(function(){
                        /*$state.go('main.sys.user.list');*/
                    },2000);
                }else{
                    alert("系统出现一点小问题，请仔细检查代码修改错误！");
                    toaster.clear('*');
                    toaster.pop('error', '', result.msg);
                    $scope.isDisabled = false;
                }
                $scope.loading = false;
            }
        }

        var handleFileSelect=function(evt) {
            var file=evt.currentTarget.files[0];
            if(!/image\/\w+/.test(file.type)){
                return false;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                $scope.$apply(function($scope){
                    $scope.myImage=evt.target.result;
                });
            };
            reader.readAsDataURL(file);
        };
        angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
        $('.upload-pic-box a').click(function() {
        	$('#fileInput').click();
        });
        //重置个人信息编辑
        $scope.refresh=function () {
            activate();
        }
        // 初始化页面
        function activate() {
	        $scope.loading = true;
        	$.ajax({
        		type: 'GET',
				url : '/user/read/current'
			}).then(function(result) {
		        $scope.loading = false;
				if (result.httpCode == 200) {
                    $scope.record=result.data;
                    var bd=$scope.record.birthDay;
                    if((bd!== null && bd!== undefined && bd!== "")){
                     var t=bd.split(" ");
                        document.getElementById("birthDay").value=t[0];
                    }else{/*alert("出生日期为空");*/}
                    //document.getElementById("birthDay").value=$scope.record.birthDay;
                    //设置性别
                    $(":radio[name='sex'][value='" + $scope.record.sex + "']").prop("checked", "checked");
				} else {
                    $scope.msg = result.msg;
				}
				$scope.$apply();
	            $timeout(function(){
	                $scope.myCroppedImage=$scope.record.avatar || defaultAva;//初始化 预览图
	                $scope.record.avatar = null;
	            },300);
			});
        }
        

        //表单验证
        function validate(){
            //notEqual 规则
            $.validator.addMethod('notEqual', function(value, ele){
                return value != this.settings.rules[ele.name].notEqual;
            });
            jQuery('form').validate({
                rules: {
                    namePinyin: {
                        pinyinCheck:[],
                        maxlength:20
                    },
                    idCard: {
                        isIdCardNo: []
                    },
                    address: {
                        maxlength:255
                    },
                    email: {
                        required:true,
                        email:true
                    },
                    phone: {
                        required:true,
                        isPhone:[]
                    }
                },
                messages: {
                   namePinyin: {
                     pinyinCheck: '请输入拼音',
                     maxlength:'长度不能超过20个字符'
                     } ,
                     idCard: {
                     isIdCardNo: '请正确填写身份证号码'
                     },
                     address: {
                     maxlength: '填写字符不能超过255个'
                     },
                     email:{
                     required:'请填写邮件',
                     email: '请正确填写邮箱'
                     },
                     phone:{
                     required:'请填写联系电话',
                     isPhone: '请正确填写联系电话'
                     }
                },
                submitHandler: function() {
                    saveData();
                }
            });
        }

    }]);